package com.mryan.ps_auth.service;

import com.mryan.ps_auth.manager.UserManager;
import com.mryan.ps_common.entity.PSAuthUser;
import com.mryan.ps_common.entity.system.SystemUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_auth.service
 * @Author: Yan
 * @CreateTime: 2021-04-23 21:08
 * @Description: 用于校验用户名和密码的类
 */
@Service
public class PSUserDetailService implements UserDetailsService {
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private UserManager userManager;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SystemUser systemUser = userManager.findByName(username);
		if (systemUser != null) {
			String permissions = userManager.findUserPermissions(systemUser.getUsername());
			boolean notLocked = false;
			if (StringUtils.equals(SystemUser.STATUS_VALID, systemUser.getStatus()))
				notLocked = true;
			PSAuthUser authUser = new PSAuthUser(systemUser.getUsername(), systemUser.getPassword(), true, true, true, notLocked,
					AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));

			BeanUtils.copyProperties(systemUser,authUser);
			return authUser;
		} else {
			throw new UsernameNotFoundException("");
		}
	}

}
